console.log('载入backgroundJs');
// 监听来自content-script的消息
// chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//     debugger;
//     const { url } = request;
//     sendResponse(JSON.stringify(api[url]()));
// });

// const api = {
//     '/getUserList': () => {
//         const users = JSON.parse(localStorage.getItem('userList')) || {};
//         return users.rows || '';
//     },
// };
export const ENVDATAList = 'ENVDATAList'
export const USERList = 'USERList'
export const USERAUTO = 'USERAUTO'

chrome.contextMenus.create({
    id: 'NCCRoot',
    title: "NCC环境列表",
    contexts: ["all"],
    onclick: function () { alert('您点击了右键菜单！'); }
});





getData(ENVDATAList).then(data => {
    console.log('data',data)
    data.forEach(tag => {
        let { title, href, selectedUser} = tag
        chrome.contextMenus.create({
            "parentId": "NCCRoot",
            "id": href,
            "title": title,
            onclick: function () { 
                let url = tag.href
                if (tag.selectedUser) {
                    let user = tag.selectedUser.split('/')
                    url += `?name=${user[0]}&pwd=${user[1]}`
                }    
                window.open(`${url}`, '_blank')   
             }
        });        
    });
})


getNCJSON().then(data => {
    data.forEach(tag => {
        let { title, href, selectedUser} = tag
        chrome.contextMenus.create({
            "parentId": "NCCRoot",
            "id": href,
            "title": title,
            onclick: function () { 
                let url = tag.href
                if (tag.selectedUser) {
                    let user = tag.selectedUser.split('/')
                    url += `?name=${user[0]}&pwd=${user[1]}`
                }    
                window.open(`${url}`, '_blank')   
             }
        });        
    });
})


export async function getData(key) {
    return new Promise((resolve) => {
        chrome.storage.local.get([key], function (res) {
            resolve(res[key])
        });
    }).catch(() => {

    })
}
export async function getNCJSON() {
    return new Promise((resolve) => {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', `https://youhanghang.gitee.io/data/NCC.json?t=${Date.now()}`, true);
        // 禁用缓存
        // xhr.setRequestHeader('cache-control', 'no-cache');        
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = JSON.parse(xhr.responseText)
                console.log('data',data)
                // 在此处使用获取到的数据
                resolve(data)
            }
        };
        xhr.send();
    }).catch(() => {

    })
}


